package com.android.support.lib.universal.view.viewpager;

import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;

import com.android.support.lib.universal.listenner.ListennerLi;
import com.android.support.lib.universal.listenner.ListennerLv;

/**
 * MyViewPager的滑动改变事件，这只是基本模板，可以根据需求再继承重写
 * 简单使用说明：
 * viewPager.setOnPageChangeListener(new MyOnPageChangeListener(viewPager, indicator, true));//给滑动效果添加事件
 *
 * @author 彭治铭
 */
public class MyOnPageChangeListener implements OnPageChangeListener {

    MyViewPager viewPager = null;
    CustomIndicator indicator = null;// 小圆点
    int current = 0;// 当前选中页
    Handler mHandler;
    Boolean bool;
    long delayMillis = 2500;//线程时间

    ListennerLi listennerLi;

    /**
     * @param viewPager   自定义的MyViewPager,没有可为null
     * @param indicator   小圆点，没有可为null
     * @param bool        是否自动滑动
     * @param listennerLi 回调事件。当新的页面被选中时调用，参数为当前滑动下标。可为null
     */
    public MyOnPageChangeListener(MyViewPager viewPager,
                                  CustomIndicator indicator, Boolean bool, ListennerLi listennerLi) {
        super();
        this.viewPager = viewPager;
        this.indicator = indicator;
        this.bool = bool;
        this.listennerLi = listennerLi;
        if (bool) {
            // 自动滑动
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    // TODO Auto-generated method stub
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case 0:
                            MyOnPageChangeListener.this.current++;
                            MyOnPageChangeListener.this.viewPager
                                    .setCurrentItem(MyOnPageChangeListener.this.current);
                            break;

                        default:
                            break;
                    }
                }
            };
            mHandler.sendEmptyMessageDelayed(0, delayMillis);
        }
    }

    // 当滑动状态改变时调用
    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    // 当当前页面被滑动时调用
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    // 当新的页面被选中时调用
    @Override
    public void onPageSelected(int arg0) {
        // TODO Auto-generated method stub
        if (bool) {
            if (indicator != null) {
                indicator.setCurrentPosition(arg0 % Config.countDot);// 同步小圆点的位置
            }
            current = arg0;
            if (mHandler != null) {
                mHandler.removeMessages(0);// 防止线程错乱
                mHandler.sendEmptyMessageDelayed(0, delayMillis);// 自动滑动
            }
        }
        if (listennerLi != null) {
            listennerLi.OnResult(arg0);
        }
    }

}
